package com.xmim.server.serialization;


import com.xmim.core.entity.Message;
import com.xmim.fulcrum.FulcrumCodec;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * User:cool coding
 * Date:2018/1/7
 * Time:21:27
 * 解码
 */
@Slf4j
public class ProtobufDecoder extends ByteToMessageDecoder {

    private final FulcrumCodec fulcrumCodec;

    public ProtobufDecoder(FulcrumCodec fulcrumCodec) {
        this.fulcrumCodec = fulcrumCodec;
    }
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
        try {
            if (in.readableBytes() < 4) {
                return;
            }
            in.markReaderIndex();
            int dataLength = in.readInt();
            if (dataLength < 0) {
                ctx.close();
            }
            if (in.readableBytes() < dataLength) {
                in.resetReaderIndex();
                return;
            }
            byte[] data = new byte[dataLength];
            in.readBytes(data);
            Object obj = fulcrumCodec.decode(data, Message.class);
            out.add(obj);
        } catch (Exception e) {
            log.debug("解译数据异常", e);
        }
    }

    @Override
    public boolean isSharable() {
        return super.isSharable();
    }
}
